/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.eng.scc.core.view;

import com.eng.scc.core.data.Company;
import com.eng.scc.core.data.Driver;
import com.eng.scc.core.db.manager.service.FuelControllerManagerService;
import com.eng.scc.core.details.CompanyDetails;
import com.eng.scc.core.details.DriverDetails;
import com.eng.scc.core.editors.DriverEditor;
import com.eng.scc.core.parts.AbstractApplicationAction;
import com.eng.scc.core.parts.ActionCategory;
import com.eng.scc.core.parts.DriversTree;
import com.eng.scc.core.parts.SummaryPane;
import com.eng.scc.core.util.HTMLFactory;
import com.eng.scc.core.util.ImageFinder;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import javax.swing.*;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;

/**
 *
 * @author Rafael
 */
public class DriverApplicationView extends ApplicationView
{

    public DriverApplicationView()
    {
        initComponets();
    }

    @Override
    public void refreshContent()
    {
        try
        {
            TreePath tp = driversTree.getSelectionPath();
            
            driversTree.buildTree();
            
            if ( tp != null )
            {
                driversTree.setSelectionPath( tp );
            }
        }
        
        catch ( Exception e )
        {
            ApplicationContext.getInstance().saveLog( e );
        }
    }
    
    private void find()
    {
        DefaultMutableTreeNode selectedNode = null;
        if ( this.driversTree.getSelectionPath() != null )
        {
             selectedNode = ( DefaultMutableTreeNode)this.driversTree.getSelectionPath().getLastPathComponent();
        }
            boolean result = false;
            boolean helper = false;

            TreePath path = null;

            DefaultMutableTreeNode firstNodeFound = null;

            if ( ! tfSearch.getText().isEmpty() )
            {
                DefaultMutableTreeNode root = (DefaultMutableTreeNode) driversTree.getModel().getRoot();

                Enumeration e = root.breadthFirstEnumeration();

                while ( e.hasMoreElements() )
                {
                    DefaultMutableTreeNode node = (DefaultMutableTreeNode) e.nextElement();

                    if ( selectedNode != null && 
                         node == selectedNode )
                    {
                        helper = true;
                    }

                    else
                    {
                        if ( node.getUserObject() instanceof Company )
                        {
                            Company c = (Company) node.getUserObject();

                            if ( c.getRealName().toLowerCase().contains( tfSearch.getText().trim().toLowerCase() ) || 
                                 c.getFantasyName().toLowerCase().contains( tfSearch.getText().trim().toLowerCase() ) )
                            {
                                if ( helper )
                                {
                                    result = true;
                                    path = new TreePath( node.getPath() );
                                    break;
                                }

                                else if ( firstNodeFound == null )
                                {
                                    firstNodeFound = node;
                                }
                            }
                        }

                        else if ( node.getUserObject() instanceof Driver )
                        {
                            Driver c = (Driver) node.getUserObject();
                            
                            if ( c.toString().toLowerCase().contains( tfSearch.getText().trim().toLowerCase() ) )
                            {
                                if ( helper )
                                {
                                    result = true;
                                    path = new TreePath( node.getPath() );
                                    break;
                                }

                                else if ( firstNodeFound == null )
                                {
                                    firstNodeFound = node;
                                }
                            }
                        }
                    }
                }

                if ( path == null )
                {
                    if ( firstNodeFound != null )
                    {
                        path = new TreePath( firstNodeFound.getPath() );
                    }

                    else if ( selectedNode != null )
                    {
                        path = new TreePath( selectedNode.getPath() );

                        if ( ! result )
                        {
                            JOptionPane.showMessageDialog( this, "Nenhum resultado encontrado para: " + tfSearch.getText() );
                        }
                    }

                    else
                    {
                        JOptionPane.showMessageDialog( this, "Nenhum resultado encontrado para: " + tfSearch.getText() );
                    }
                }

                driversTree.expandPath( path );
                driversTree.setSelectionPath( path );
                driversTree.scrollPathToVisible( path );
//            }
        }
    }

    private void updateItemSelected()
    {
        try
        {
            Object o = getSelectedObject();

            if ( o instanceof Company )
            {
                summaryPane.setContent( CompanyDetails.getDetails( ( Company ) o ) );
            }
            else if ( o instanceof Driver )
            {
                summaryPane.setContent( DriverDetails.getDetails( ( Driver ) o ) );
            }
            else
            {
                summaryPane.setContent( HTMLFactory.Body.EMPTY );
            }
        }
        
        catch ( Exception e )
        {
            ApplicationContext.getInstance().saveLog( e );
        }
    }
    
    private void initComponets()
    {
       setLayout( new GridBagLayout() );
       
       btSearch.setIcon( ImageFinder.getImageIcon( "bt_search.png") );
       
       btSearch.addActionListener( new ActionListener() 
       {
            @Override
            public void actionPerformed( ActionEvent e )
            {
                find();
            }
        });
       
       tfSearch.addActionListener( new ActionListener() 
       {
            @Override
            public void actionPerformed( ActionEvent e )
            {
                find();
            }
        });

        add( lbSearch, 
                new GridBagConstraints( 1, 0, 1, 1, 0.0, 0.0,
                                        GridBagConstraints.WEST, 
                                        GridBagConstraints.NONE, 
                                        new Insets( 5, 5, 5, 5 ), 0, 0 ) );
        add( tfSearch, 
                new GridBagConstraints( 2, 0, 1, 1, 1.0, 0.0,
                                        GridBagConstraints.WEST, 
                                        GridBagConstraints.HORIZONTAL, 
                                        new Insets( 5, 5, 5, 5 ), 0, 0 ) );
        add( btSearch, 
                new GridBagConstraints( 3, 0, 1, 1, 0.0, 0.0, 
                                        GridBagConstraints.WEST, 
                                        GridBagConstraints.NONE, 
                                        new Insets( 5, 5, 5, 5 ), 0, 0 ) );
        
        paneScroll.setViewportView( driversTree );
//        add( paneScroll, 
//                new GridBagConstraints( 1, 1, 3, 1, 1.0, 1.0, 
//                                        GridBagConstraints.NORTH, 
//                                        GridBagConstraints.BOTH, 
//                                        new Insets( 5, 5, 5, 5 ), 0, 0 ) );
        
        splitPane.setLeftComponent( paneScroll );
        splitPane.setDividerLocation( 0.2 );
        splitPane.setRightComponent( summaryPane );
        
        add( splitPane, 
                new GridBagConstraints( 1, 1, 3, 1, 1.0, 1.0, 
                                        GridBagConstraints.NORTH, 
                                        GridBagConstraints.BOTH, 
                                        new Insets( 5, 5, 5, 5 ), 0, 0 ) );
        
        driversTree.addTreeSelectionListener( new TreeSelectionListener()
        {
            @Override
            public void valueChanged( TreeSelectionEvent e )
            {
                updateItemSelected();
            }
        } );
        
        driversTree.addMouseListener( new MouseAdapter()
        {
            @Override
            public void mouseClicked( MouseEvent e )
            {
                if ( e.getClickCount() >= 2 )
                {
                    if ( getSelectedObject() instanceof Driver )
                    {
                        edit();
                    }
                }
            }
        });
    }
    
    public void add()
    {
        try
        {   
            if ( DriverEditor.edit( this, new Driver() ) )
            {
                refreshContent();
            }
        }
        
        catch ( Exception e )
        {
            ApplicationContext.getInstance().saveLog( e );
        }
    }
    
    public void delete()
    {
        if ( getSelectedObject() != null && getSelectedObject() instanceof Driver )
        {
            try
            {
                if ( JOptionPane.showConfirmDialog( this, "Deseja excluir o Motorista selecionado?" ) == JOptionPane.YES_OPTION )
                {
                    FuelControllerManagerService.getInstance().deleteDriver( ( Driver) getSelectedObject() );

                    refreshContent();
                }
            }
            
            catch ( Exception e )
            {
                ApplicationContext.getInstance().saveLog( e );
            }
        }
        
        else
        {
            JOptionPane.showMessageDialog( this, "Selecione um Motorista na tabela!" );
        }
    }    
    
    private Object getSelectedObject()
    {
        if ( driversTree.getSelectionPath() != null )
        {
//            if ( ((DefaultMutableTreeNode) driversTree.getSelectionPath().getLastPathComponent() ).getUserObject() instanceof Driver )
            {
                return ((DefaultMutableTreeNode) driversTree.getSelectionPath().getLastPathComponent() ).getUserObject();
            }
        }
        
        return null;
    }
    
    public void edit()
    {
        try
        {
            Object driver = getSelectedObject();
            
            if ( driver != null && driver instanceof Driver )
            {
                if ( DriverEditor.edit( this, ( Driver)driver ) )
                {
                    refreshContent();
                }
            }

            else
            {
                JOptionPane.showMessageDialog( this, "Selecione um Motorista!" );
            }
        }
        
        catch ( Exception e )
        {
            ApplicationContext.getInstance().saveLog( e );
        }
    }

    @Override
    public List<ActionCategory> getViewActions()
    {
        List<ActionCategory> categorys = new ArrayList<ActionCategory>();
        categorys.add( new ActionCategory( "Motoristas", new AbstractApplicationAction[]
        {
            btAdd,
            btEdit,
            btDelete,
            btPrint
        }) );
        return categorys;
    }
    
    protected AbstractApplicationAction btPrint = new AbstractApplicationAction( "Imprimir", "tb_print.png" )
    {
        @Override
        public void actionPerformed( ActionEvent e )
        {
//            Database.runReport( "full_client_report.jasper" );
        }
    };
    
    private DriversTree driversTree = new DriversTree();
    private JScrollPane paneScroll = new JScrollPane();
    private JLabel lbSearch = new JLabel( "Buscar:" );
    private JTextField tfSearch = new JTextField();
    private JSplitPane splitPane = new JSplitPane();
    private SummaryPane summaryPane = new SummaryPane();
    private JButton btSearch = new JButton();
    
//    private JButton btAdd = new JButton( "Adicionar" );
//    private JButton btEdit = new JButton( "Editar" );
//    private JButton btDelete = new JButton( "Excluir" );
}
